package com.zlyx.easy.http.handlers;

import java.util.Map.Entry;

import com.zlyx.easy.core.annotations.Brancher;
import com.zlyx.easy.core.tool.Ops;
import com.zlyx.easy.http.models.RequestModel;

/**
 * 
 * @Auth 赵光
 * @Describle
 * @2019年12月25日
 */
@Brancher(todo = { "处理get请求" }, value = "GET")
public class GetMappingHandler extends AbstractMappingHandler {

	@Override
	public Object handleMapping(String url, RequestModel rm) {
		StringBuilder sb = new StringBuilder();
		String key = null;
		String value = null;
		for (Entry<String, Object> entry : rm.getParams().entrySet()) {
			if (entry.getValue() != null) {
				key = entry.getKey();
				value = "" + entry.getValue();
				if (url.contains(":" + key)) {
					url = url.replaceAll(":" + key, "" + value);
				} else if (url.contains("{" + key + "}")) {
					url = url.replaceAll("{" + key + "}", "" + value);
				} else {
					sb.append("&" + key + "=" + value);
				}
			}
		}
		String paramString = sb.toString().replaceFirst("&", "?");
		if (!"?".equals(paramString)) {
			url += paramString;
		}
		url = handleIpAndPort(url, rm);
		Ops.getLogger(rm.getCls()).info("请求【{}】GET 地址：{}", rm.getId(), url);
		Object response = restTemplate.getForObject(url, rm.getReturnType());
		Ops.getLogger(rm.getCls()).info("请求【{}】{} 结果：{}", rm.getId(), rm.getMethod(), response);
		return response;
	}

}
